package com.ccepc.algmanage.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ccepc.algmanage.mapper.AlgorithmInfoMapper;
import com.ccepc.algmanage.service.AlgorithmInfoService;
import com.ccepc.algmanage.service.DeployInfoService;
import com.ccepc.algmanage.utils.AuthInfoUtils;
import com.ccepc.algmanage.utils.CommonUtils;
import com.ccepc.algmanage.utils.HkUtils;
import com.ccepc.demo.api.dto.AlgorithmInfoDto;
import com.ccepc.demo.api.dto.AlgorithmInfoListDto;
import com.ccepc.demo.api.entity.AlgorithmInfo;
import com.ccepc.demo.api.entity.DeployInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;

/**
 *
 *
 * @author pigx code generator
 * @date 2023-11-06 13:52:35
 */
@Service
@Slf4j
public class AlgorithmInfoServiceImpl extends ServiceImpl<AlgorithmInfoMapper, AlgorithmInfo> implements AlgorithmInfoService {
    @Resource
    private DeployInfoService deployInfoService;

    @Transactional
    @Override
    public Object removeBatch(AlgorithmInfoListDto algorithmInfoListDto) {
        List<AlgorithmInfo> algList = algorithmInfoListDto.getAlgorithmInfoList();
        HkUtils hkUtils = new HkUtils(algorithmInfoListDto.getHkAuths());
        algList.forEach(alg -> {
            Integer algId = alg.getId();
            String eventCodes = this.getById(algId).getEventCode();
            deployInfoService.removeBatch(
                    deployInfoService.list(
                            new LambdaQueryWrapper<DeployInfo>()
                                    .eq(DeployInfo::getAlgorimId, algId)
                    )
            );
            String[] eventCodeList = eventCodes.split(",");
            for (String eventCode : eventCodeList) {
                // 取消事件订阅
                hkUtils.eventUnSubscriptionByEventTypes(Integer.parseInt(eventCode));
            }
            this.removeById(algId);
        });
        return true;
    }

    @Override
    public Object getAlgPage(Page page, AlgorithmInfo algorithmInfo) {
        LambdaQueryWrapper<AlgorithmInfo> wrapper = new LambdaQueryWrapper<>();
        String algName = algorithmInfo.getAlgName();
        if (algName != null && !algName.isEmpty()) {
            wrapper.like(AlgorithmInfo::getAlgName, algName);
        }
        wrapper.eq(AlgorithmInfo::getTenantId, AuthInfoUtils.getTenantId());
        return this.page(page, wrapper);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public Object saveAndSubs(AlgorithmInfoDto algorithmInfoDTO) {
        HkUtils hkUtils = new HkUtils(algorithmInfoDTO.getHkAuths());
        AlgorithmInfo algorithmInfo = algorithmInfoDTO.getAlgorithmInfo();
        // 如果有id则查出旧的事件码
        String oldEventCodes = null;
        if (algorithmInfo.getId() != null) {
            oldEventCodes = this.getById(algorithmInfo.getId()).getEventCode();
        }
        String eventCodes = CommonUtils.initListString(algorithmInfo.getEventCode());
        algorithmInfo.setEventCode(eventCodes);
        int saveOrUpdate = CommonUtils.saveOrUpdate(algorithmInfo, this);
        // 新增或修改数据
        if (saveOrUpdate == -1) {
            log.info("新增或修改失败");
            return false;
        } else if (saveOrUpdate == 0 && algorithmInfo.getAppId() == null) {
            DeployInfo deployInfo = new DeployInfo();
            deployInfo.setAlgorimId(algorithmInfo.getId());
            CommonUtils.saveOrUpdate(deployInfo, deployInfoService);
        }
        String[] eventCodeList = eventCodes.split(",");
        for (String eventCode : eventCodeList) {
            // 新增或修改成功，订阅事件
            hkUtils.eventSubscriptionByEventTypes(Integer.parseInt(eventCode));
        }
        if (oldEventCodes != null) {
            String[] oldEventCodeList = oldEventCodes.split(",");
            // 如果是事件发生更改，且旧的事件码在数据库中不存在。则取消旧事件码订阅
            for (String oldEventCode : oldEventCodeList) {
                int count = this.count(
                        new LambdaQueryWrapper<AlgorithmInfo>()
                                .like(AlgorithmInfo::getEventCode, oldEventCode)
                );
                if (count == 0) {
                    hkUtils.eventUnSubscriptionByEventTypes(Integer.parseInt(oldEventCode));
                }
            }
        }
        return true;
    }
}
